package com.sikaryofficial.adaptermq.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONReader;
import com.baomidou.mybatisplus.extension.service.IService;
import com.sikaryofficial.adaptermq.constant.TableMapperEnum;
import com.sikaryofficial.adaptermq.message.body.SyncDataMessage;
import com.sikaryofficial.adaptermq.service.*;
import com.sikaryofficial.common.core.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author : qinjinyuan
 * @desc :  数据同步核心处理类
 * @date : 2024/04/30 8:46
 */
@Service
@Slf4j
@SuppressWarnings(value = "unchecked")
public class SyncServiceImpl implements ISyncService {
    private static final String SYNC_TYPE_INSERT = "INSERT";
    private static final String SYNC_TYPE_UPDATE = "UPDATE";
    private static final String SYNC_TYPE_DELETE = "DELETE";
    @Override
    public void processData(SyncDataMessage message) {
        String tableName = message.getTable();
        // 构建映射表
        Map<String, TableMapperEnum> tableMapperEnumMap = TableMapperEnum.buildAllTableInfo();
        TableMapperEnum tableMapperEnum = MapUtils.getObject(tableMapperEnumMap, tableName);
        // 验证 tableName，确保它是预期的值
        if (Objects.isNull(tableMapperEnum)) {
            log.error("Invalid table name: " + tableName);
            return;
        }
        try {
            executeByMapper(tableMapperEnum, message);
        } catch (NoSuchBeanDefinitionException e) {
            log.error("Bean not found: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Error processing data: " + e.getMessage());
        }
    }

    private void executeByMapper(TableMapperEnum tableMapperEnum, SyncDataMessage message) throws NoSuchBeanDefinitionException {
        IService service = null;
        List<JSONObject> data = message.getData();
        String type= message.getType();
        // 假设配置文件中存储了JSON字符串
        String jsonString = data.toString();
        switch (tableMapperEnum) {
            case ARTICLE:
                service = SpringUtils.getBean(IArticleService.class);
                log.info("Processing article data");
                break;
            case ARTICLE_CATEGORY:
                service = SpringUtils.getBean(IArticleCategoryService.class);
                break;
            case ARTICLE_CATEGORY_MAPPER:
                service = SpringUtils.getBean(IArticleCategoryMappingService.class);
                break;
            case ARTICLE_EVALUATE:
                service = SpringUtils.getBean(IArticleEvaluateService.class);
                break;
            case ARTICLE_EVALUATE_REPLY:
                service = SpringUtils.getBean(IArticleEvaluateReplyService.class);
                break;
            case ARTICLE_EXPOSURE_DAILY:
                service = SpringUtils.getBean(IArticleExposureCountService.class);
                break;
            case ARTICLE_VIEWS:
                service = SpringUtils.getBean(IArticleViewsService.class);
                break;
            case FOLLOW:
                service = SpringUtils.getBean(IFollowService.class);
                break;
            case MY_STATISTICS:
                service = SpringUtils.getBean(IMyStatisticsService.class);
                break;
            case USER_ACTION:
                service = SpringUtils.getBean(IUserActionService.class);
                break;
            case USER_SHIELD:
                service = SpringUtils.getBean(IUserShieldService.class);
                break;
            case ATTACHMENT:
                service = SpringUtils.getBean(IAttachmentService.class);
                break;
            case SYS_USER:
                service = SpringUtils.getBean(ISysUserService.class);
                break;
            case SYS_USER_DAILY:
                service = SpringUtils.getBean(ISysUserDailyService.class);
                break;
            case GOODS:
                service = SpringUtils.getBean(IGoodsService.class);
                break;
            case GOODS_RELATION:
                service = SpringUtils.getBean(IGoodsRelationService.class);
                break;
            default:
                log.error("Unsupported table mapper enum: " + tableMapperEnum.name());
                return;
        }
        boolean updateFlag = SYNC_TYPE_INSERT.equals(type) ||
                SYNC_TYPE_UPDATE.equals(type) ;
        boolean deleteFlag = SYNC_TYPE_DELETE.equals(type);
        if (updateFlag) {
            service.saveOrUpdateBatch(JSONArray.parseArray(jsonString, tableMapperEnum.getEntityClazz(), JSONReader.Feature.SupportSmartMatch));
        }
        if (deleteFlag) {
            List<Object> deleteIds = Lists.newArrayList();
            String pkName = message.getPkNames()[0];
            message.getData().forEach(item-> deleteIds.add(item.get(pkName)));
            service.removeByIds(deleteIds);
        }
    }

    /**
     * {"data":[{"article_evaluate_reply_id":"1782396909416161281",
     * "article_evaluate_id":"7186255432686637056","reply_type":"0","reply_content":"r333","reply_user_id":"243",
     * "reply_user_name":"ske01cx8a","tenant_id":"1","revision":null,"created_by":"243",
     * "created_time":"2024-04-22 21:11:53","updated_by":null,"updated_time":null,"deleted_version":"0","created_name":"ske01cx8a"}],
     * "database":"hismk_cloud_20240427",
     * "es":1714532576000,
     * "gtid":"",
     * "id":6,
     * "isDdl":false,
     * "mysqlType":{"article_evaluate_reply_id":"bigint unsigned","article_evaluate_id":"bigint unsigned","reply_type":"tinyint unsigned","reply_content":"varchar(1000)","reply_user_id":"bigint unsigned","reply_user_name":"varchar(100)","tenant_id":"int unsigned","revision":"int unsigned","created_by":"bigint unsigned","created_time":"datetime","updated_by":"bigint unsigned","updated_time":"datetime","deleted_version":"bigint unsigned","created_name":"varchar(100)"},
     * "old":null,
     * "pkNames":["article_evaluate_reply_id"],
     * "sql":"",
     * "sqlType":{"article_evaluate_reply_id":-5,"article_evaluate_id":-5,"reply_type":-6,"reply_content":12,"reply_user_id":-5,"reply_user_name":12,"tenant_id":4,"revision":4,"created_by":-5,"created_time":93,"updated_by":-5,"updated_time":93,"deleted_version":-5,"created_name":12},
     * "table":"article_evaluate_reply_t",
     * "ts":1714532576919,
     * "type":"DELETE"
     * }
     */
}
